import React from "react";
import {withRouter} from 'react-router-dom'
import TeamAvatar from "../../../Header/Versus/TeamAvatar/TeamAvatar";
import CustomBotton from "../../../../../../shared-components/CustomButton/CustomBotton";
import {votTeamReq, zanzuReq} from "../../../../../../apis/goApis";
import LocalStorageService from "../../../../../../utils/LocalStorageService";
import {Toast} from "antd-mobile";
import vsIconSrc from "../../../../../../../src/res/images/web/together/vs-icon.png"
import CountDisplay from "../../chat-room/GiftPopup/GiftCount/CountDisplay/CountDisplay";
import 赠盲盒src from '../../../../../../../src/res/images/web/together/赠盲盒@2x.png'
import selectHomeSrc from '../../../../../../../src/res/images/web/together/未选-红赞@2x.png'
import selectAawySrc from '../../../../../../../src/res/images/web/together/未选-红赞备份@2x.png'
import seatSrc from '../../../../../../../src/res/images/web/together/seat@2x.png'
import foldedIconSrc from '../../../../../../../src/res/images/web/together/little triangle red备份 16@2x.png'
import fuliLightBg from '../../../../../../../src/res/images/web/together/券-点亮@2x.png'
import fuliGrayBg from '../../../../../../../src/res/images/web/together/券-未点亮@2x.png'
import fuliGiftLightSrc from '../../../../../../../src/res/images/web/together/高级礼盒-点亮@2x.png'
import fuliGiftGraySrc from '../../../../../../../src/res/images/web/together/高级礼盒-未点亮@2x.png'
import 用户未设置头像 from '../../../../../../../src/res/images/web/together/无设置头像@2x.png'
import './vote.css'
import VotedNotice from "../voted-notice/voted-notice";
import withDownload from "../../../../../../high-order-component/withDownload/withDownload";
import {log} from "../../../../../../utils/commonfunc";

class Votes extends React.Component {
    constructor(props) {
        super(props)
        this.uid = localStorage.getItem('userid')
        this.login = LocalStorageService.get('isLogin')
        this.matchId = this.props.match.params.gameId
        this.state = {
            coins: 1,
            seatFolded: true,
        }
    }
    voteTeam = (team, isHome) => {
        if (this.login) {
            const params = {
                Uid: this.uid,
                Namiid: parseInt(this.matchId),
                Teamname: team.name_zh,
                Who: isHome ? 'zhu' : 'ke',
            }
            votTeamReq(params)
                .then(resp => {
                    if (resp.data.ok) {
                        Toast.info('支持成功')
                        this.props.setVoted()
                    }
                })
        } else {
            this.props.history.push('../login')
        }
    }

    changeTotal = offset => {
        const result = this.state.coins + offset
        if (result <= 0) {
            this.setState({
                coins: 0,
            })
        } else {
            this.setState({
                coins: result,
            })
        }
    }

    zanzu = () => {
        if (this.uid && this.state.coins > 0) {
            zanzuReq({
                Uid: this.uid,
                Namiid: parseInt(this.matchId),
                Count: this.state.coins,
            }).then(res => {
                if (res.data.ok === 1) {
                    Toast.success('赞助成功', 0.5)
                }
            })
        } else if (this.state.coins === 0) {
            Toast.fail('赞助数量必须大于0')
        } else {
            Toast.fail('请登陆')
        }

    }

    renderTeamSelect(team, isHome) {
        const homeColor = '#C83736'
        const awayColor = '#2D48C8'
        return <div
            onClick={() => this.props.onVoteTeam(team, isHome)}
            style={{
                width: '100%',
                background: '#fff',
                textAlign: 'center',
                marginRight: '1px',
                padding: '20px 22px',
                marginTop: '1px',
            }}
        >
            <TeamAvatar iconUrl={team.logo} style={{margin: '0 auto',}} atTop={true}/>
            <p
                className='mg-b-8px mg-t-8px'
            >{team.name_zh}</p>
            <CustomBotton
                bg={isHome ? homeColor : awayColor}
            >
                {`支持${isHome ? '主' : '客'}队`}
            </CustomBotton>
        </div>
    }

    formatAudience (audience) {
        const fillToLength = (array, item, length) => {
            let result = [...array]
            for (let i = 0; i < length - array.length; i++) {
                result.push(item)
            }
            return result
        }
        if (audience.length >= 28) {
            return audience
        }
        let seat = {
            Iconurl: seatSrc,
            Nickname: "",
            Uid: "",
            fake: true,
        }
        return fillToLength(audience, seat, 58)
    }

    render() {
        let voted = this.props.voted
        const game = this.props.game
        const home = game.home_team
        const away = game.away_team
        const detail = this.props.voteDetail
        const result = this.props.voteResult
        const status = game.info.statusid

        const notStart = status === 1
        const isEnd = status === 8
        const gameOn = status > 1 && status < 8

        let homeCount = result?.Zhucount || 0
        homeCount += this.props.fakeHeat[0]
        let awayCount = result?.Kecount || 0
        awayCount += this.props.fakeHeat[1]
        const countTotal = homeCount + awayCount
        const isBothZero = homeCount === 0 && awayCount === 0
        const homeRate = homeCount / countTotal
        const awayRate = awayCount / countTotal
        const homePer = isBothZero
            ? '50%'
            : `${homeRate > 0.9 
                ? 90 
                : homeRate < 0.1 
                    ? 10 : homeRate * 100}%`
        const awayPer = isBothZero
            ? '50%'
            : `${awayRate > 0.9 
                ? 90 
                : awayRate < 0.1 
                    ? 10 
                    : awayRate * 100}%`
        const voteTemplate = <div className='flex-space-between-align-center'>
            {this.renderTeamSelect(home, true)}
            {this.renderTeamSelect(away, false)}
        </div>
        const homeVoted = detail?.Who === 'zhu'
        const awayVoted = detail?.Who === 'ke'
        const homeColor = '#CA3A39'
        const awayColor = '#2D48C8'
        const avatarStyle = {
            borderRadius: '50%',
            border: '2px solid',
            background: '#fff',
            overflow: 'hidden',
            width: 50,
            minWidth: 50,
            height: 50,
            transition: 'none',
            zIndex: 2,
        }
        let iconLeft = homePer
        if (isBothZero) {
            iconLeft = '50%'
        }
        if (homeCount / countTotal > 0.9) {
            iconLeft = '90%'
        }
        if (awayCount / countTotal > 0.9) {
            iconLeft = '10%'
        }
        const teamVs = <div className='flex-space-between-align-center mg-b-16px' style={{width: '100%',}}>

            <div className={homeVoted ? 'vote-team voted-team-home': 'vote-team'}>
                <TeamAvatar atTop={true} iconUrl={home.logo} style={{...avatarStyle, borderColor: detail?.Who === 'zhu' ? homeColor : '#E4E4E4'}}/>
                {gameOn && !voted && !homeVoted ? <img onClick={() => this.props.onVoteTeam(home, true)} src={selectHomeSrc} alt='' style={{width: 28, height: 28, position: 'absolute', bottom: '-10px', left: '50%', transform: 'translateX(-50%)',}}/> : null}
                {homeVoted ? <span style={{zIndex: 3, position: 'absolute', fontSize: '10px', bottom: '4px', left: '50%', transform: 'translateX(-50%)', color: '#fff',}}>我方</span> : null}
                {/*{this.props.svgaHome}*/}
            </div>

            <div
                style={{
                    height: 24,
                    background: '#fff',
                    width: '100%',
                    position: "relative",
                    margin: '0 -3px',
                }}
                className='flex'
            >
                <div
                    style={{
                        background: 'linear-gradient(90deg, #C83736, #E66866)',
                        height: '24px',
                        width: homePer,
                        transition: 'all 0.5s',
                        minWidth: '10%',
                        paddingLeft: '11px',
                    }}
                >
                    <span style={{color: '#fff', lineHeight: '24px',}}>{homeCount}</span>
                </div>
                <img alt="" src={vsIconSrc} style={{width: 20, height: 24, position: 'absolute', left: iconLeft, transform: 'translateX(calc(-50%))', transition: 'all 0.5s'}}/>
                <div
                    style={{
                        background: 'linear-gradient(90deg, #597EE6, #2D48C8)',
                        height: '24px',
                        width: awayPer,
                        transition: 'all 0.5s',
                        minWidth: '10%',
                        textAlign: 'right',
                        paddingRight: '11px',
                    }}
                >
                    <span style={{color: '#fff',lineHeight: '24px',}}>{awayCount}</span>
                </div>
            </div>
            <div  className={awayVoted ? 'vote-team voted-team-away': 'vote-team'}>
                <TeamAvatar atTop={true} iconUrl={away.logo} style={{...avatarStyle, borderColor: detail?.Who === 'ke' ? awayColor : '#E4E4E4'}}/>
                {awayVoted ? <span style={{zIndex: 3, position: 'absolute', fontSize: '10px', bottom: '4px', left: '50%', transform: 'translateX(-50%)', color: '#fff',}}>我方</span> : null}
                {gameOn && !voted && !awayVoted ? <img src={selectAawySrc} onClick={() => this.props.onVoteTeam(away, false)} alt='' style={{width: 28, height: 28, position: 'absolute', bottom: '-10px', left: '50%', transform: 'translateX(-50%)',}}/> : null}
                {/*{this.props.svgaAway}*/}
            </div>
        </div>

        const fuliNotStart = <div
            style={{
                background: '#F9F9F9',
                textAlign: "center",
            }}
            className='pd-12 mg-t-16px'
        >
            <p
                style={{
                    fontSize: '16px',
                    fontWeight: 'bold',
                    color: '#333333',
                    lineHeight: '22px',
                }}
            >- 福利大奖 -</p>
            <p className='gray-text mg-t-8px'>本场总热度达到一定值，能解锁不同的福利大奖，当支持的球队获胜时，你将有机会获得奖励。现在购买一份赞助可为球队增加10点热度，同时赠送一次盲盒开奖机会哦！</p>
            <div style={{width: 192, margin: '28px auto 16px',}}>
                <CountDisplay
                    changeTotal={this.changeTotal}
                    total={this.state.coins}
                    countWidth='112px'
                />
            </div>
            <div style={{width: '100%', textAlign: 'center', position: 'relative'}} className='mg-b-16px'>
                <span style={{color: '#FFA500',}}>{this.state.coins * 10}金币</span>
                <span style={{position: 'absolute', left: '75%', top: '50%', transform: 'translate(-50%, -50%)',}}
                      className='gray-text flex-align-center' >
                    赠
                    <img src={赠盲盒src} style={{width: 20, height: 22, margin: '0 4px 0 8px',}} alt=''/>
                    x{this.state.coins}
                </span>
            </div>

            <CustomBotton
                bg='#FFA500'
                onClick={() => this.zanzu()}
            >
                赞助我方
            </CustomBotton>

        </div>

        const fulis = this.props.fuli

        const fuliTemplate = notStart
            ? fuliNotStart
            : <div className='flex-align-center mg-b-8px' style={{overflowX: 'scroll',}}>
                <span className='no-break' style={{marginRight: '8px',}}>福利</span>
                <div className='flex'>
                    {fulis.map((fuli, index) => {
                        const isLighted = index <= this.props.fuliLight
                        const votedFuli = <div
                            key={index}
                            onClick={() => this.props.history.push('../fuli/' + this.matchId)}
                            style={{
                                width: 76,
                                background: isLighted? '#FFE6E6' : '#F1F1F1',
                                borderRadius: '2px',
                                marginRight: '4px',
                                padding: '4px 0',
                                textAlign: 'center',
                                color: isLighted ? '#CA3A39' : 'rgba(51, 51, 51, 0.4)',
                                fontSize: '14px',
                            }}>
                            <span style={{fontSize: '10px', marginRight: '4px',}}>{fuli.Name}</span>
                            <span style={{fontWeight: 'bold',}}>{fuli.Quota}元</span>
                        </div>
                        const unVotedFuli = <div
                            key={index}
                            style={{
                                width: 144,
                                height: 35,
                                background: `no-repeat url(${isLighted ? fuliLightBg : fuliGrayBg}) 50% 50%/cover`,
                                marginLeft: '4px',
                                padding: '8px',
                                color: isLighted ? '#CA3A39' : 'rgba(51, 51, 51, 0.4)',
                                fontSize: '14px',
                            }}
                            className="flex-align-center"
                            onClick={() => this.props.callVoteModal()}
                        >
                            <img src={isLighted ? fuliGiftLightSrc : fuliGiftGraySrc} alt='' style={{width: 21, height: 24, marginRight: '4px',}}/>
                            <div>
                                <p style={{fontSize: '10px',}}>{`Lv.${index + 1}`}</p>
                                <span style={{fontSize: '10px', marginRight: '4px',}}>{fuli.Name}</span>
                                <span style={{fontWeight: 'bold',}}>{fuli.Quota}元</span>
                            </div>
                        </div>
                        return voted ? votedFuli : unVotedFuli
                    })}
                </div>

            </div>
        const audience = this.formatAudience(this.props.audience)
        const showAtWatch = voted && audience.findIndex(a => a.Uid === LocalStorageService.get('userid')) === -1


        const vips = audience.slice(0, 8)
        const insides = audience.slice(8, 28)
        const watchers = audience.slice(28, 58)

        let maxSeatsHei = window.innerHeight - 220 - 43.5 - 72 - 24 - 60
        if (this.props.downloadShow) {
            maxSeatsHei = maxSeatsHei - 60
        }

        const seats = <div
            style={{
                height: this.state.seatFolded ? '0' : '233px',
                maxHeight: maxSeatsHei,
                transition: 'all 1s',

                overflow: "hidden",
                overflowY: "scroll",
            }}
        >

            <div
                className='fade-in'
                style={{
                    display: this.state.seatFolded ? 'none' : '',
                }}
            >
                {detail && !isEnd && fuliTemplate}
                <div className='flex-space-between-align-center mg-b-12px'>
                    <p>主/客场云座位席</p>
                    <span className='gray-text'>{this.props.audience.length}人已入场</span>
                </div>
                <div className='flex-space-between-align-center mg-b-12px'>
                    <div className='flex-space-between-align-center'>
                        {vips.slice(0, 4).map((vip, index) => <div
                            key={index}
                            style={{
                                width: 36,
                                height: 36,
                                marginRight: '4px',
                                borderRadius: '50%',
                                background: `no-repeat url(${vip.Iconurl}) 50% 50%/cover`
                            }}
                        />)}
                    </div>
                    <p style={{fontSize: '10px', width: '14px', color: '#FFA500', lineHeight: '14px',}}>
                        VIP席
                    </p>
                    <div className='flex-space-between-align-center'>
                        {vips.slice(4).map((vip, index) => <div
                            key={index}
                            style={{
                                width: 36,
                                height: 36,
                                marginLeft: '4px',
                                background: `no-repeat url(${vip.Iconurl}) 50% 50%/cover`
                            }}
                        />)}
                    </div>
                </div>
                <div className='flex-space-between-align-center mg-b-12px'>
                    <div className='flex-space-between-align-center flex-wrap-container' style={{width: '160px',}}>
                        {insides.slice(0, 10).map((vip, index) => <div
                            key={index}
                            style={{
                                width: 28,
                                height: 28,
                                marginRight: '4px',
                                background: `no-repeat url(${vip.Iconurl}) 50% 50%/cover`,
                                marginBottom: '4px',
                            }}
                        />)}
                    </div>
                    <p style={{fontSize: '10px', width: '14px', lineHeight: '14px',}}>
                        内场席
                    </p>
                    <div className='flex-align-center flex-wrap-container' style={{width: '160px',}}>
                        {insides.slice(10, 20).map((vip, index) => <div
                            key={index}
                            style={{
                                width: 28,
                                height: 28,
                                marginLeft: '4px',
                                background: `no-repeat url(${vip.Iconurl}) 50% 50%/cover`,
                                marginBottom: '4px',
                            }}
                        />)}
                    </div>
                </div>

                <div className='flex-space-between-align-center'>
                    <div className='flex-space-between-align-center flex-wrap-container' style={{width: '160px',}}>
                        {watchers.map((vip, index) => <div
                            key={index}
                            style={{
                                width: '14px',
                                height: '14px',
                                marginBottom: '2px',
                                background: homeVoted ? '#FFBBBB' : '#BDC8FF',
                                borderRadius: '2px',
                                marginRight: '2px',
                            }}
                        />)}
                    </div>
                    <p style={{fontSize: '10px', width: '14px', lineHeight: '14px',}}>
                        看台席
                    </p>
                    <div className='flex-space-between-align-center flex-wrap-container' style={{width: '160px',}}>
                        {watchers.map((vip, index) => <div
                            key={index}
                            style={{
                                width: '14px',
                                height: '14px',
                                marginBottom: '2px',
                                background: homeVoted ? '#FFBBBB' : '#BDC8FF',
                                borderRadius: '2px',
                                marginLeft: '2px',
                            }}
                        />)}
                    </div>
                </div>

            </div>
        </div>

        const seatTemplate = <div
            style={{
                background: '#fff',
            }}
        >
            {seats}
            <div style={{width: '100%', textAlign: 'center',}} onClick={() => this.setState({seatFolded: !this.state.seatFolded,})}>
                <img src={foldedIconSrc} alt='' style={{width: 12, height: 12, transform: `rotate(${this.state.seatFolded ? '0deg' : '180deg'})`, transition: 'all 0.5s'}}/>
            </div>
        </div>

        let hei = 220 + 43.5 + 60 - 12
        if (this.props.downloadShow) {
            hei += 60
        }
        const votedTemplate = <div
            style={{
                background: '#fff',
                maxHeight: window.innerHeight - hei,
                overflow: 'hidden',
                overflowY: 'scroll',
            }}
            className='pd-12'
        >
            {detail && teamVs}
            {gameOn && voted && seatTemplate}
            {gameOn && !voted && fulis.length > 0 && fuliTemplate}
            {notStart && voted && fulis.length > 0 && fuliNotStart}
        </div>

        return <>
            {notStart && !voted ? voteTemplate : votedTemplate}
            {this.props.votedNotice && <VotedNotice
                isHome={homeVoted}
                teamData={homeVoted ? home : away}
                onVotedNoticeEnd={this.props.onVotedNoticeEnd}
            />}
        </>
    }
}

export default withRouter(withDownload(Votes))